package Jets.tick
{
	import flash.display.Shape;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.getTimer;

	public class JTick extends EventDispatcher implements InJTick
	{
		static private var _instance:JTick = null;
		/**
		 * 最大两帧间隔（防止待机后返回卡死） 
		 */
		static public var MAX_INTERVAL:int = 3000;
		static public var MIN_INTERVAL:int = 0;
		
		/**
		 * 是否停止发布Tick事件
		 * 
		 * Tick事件的发布影响的内容非常多，一般情况不建议设置此属性，而是设置所有需要暂停物品的pause属性。
		 */		
		private var ms_nPause:Boolean = false;
		private var ms_nFrameRate:Number = 24;
		private var ms_nPrevTime:int;//上次记录的时间
		private var ms_nShape:Shape;
		private var ms_nOnTimer:Function = null;
		
		static public function createTicker(onTimer:Function):JTick
		{
			if (_instance == null)
			{
				_instance = new JTick(onTimer);
			}
			return _instance;
		}
		
		static public function get instance():JTick
		{
			return _instance;
		}
		
		public function JTick(onTimer:Function)
		{
			ms_nOnTimer = onTimer;
			ms_nShape = new Shape();
			ms_nShape.addEventListener(Event.ENTER_FRAME,enterFrameHandler);
		}
		
		/**
		 * 清除掉积累的时间（在暂停之后）
		 * 
		 */
		public function clear():void
		{
			this.ms_nPrevTime = 0;
		}
		
		public function stop():void
		{
			if(ms_nShape.hasEventListener(Event.ENTER_FRAME))
			{
				ms_nShape.removeEventListener(Event.ENTER_FRAME,enterFrameHandler);
			}
		}
		
		public function start():void
		{
			if(!ms_nShape.hasEventListener(Event.ENTER_FRAME))
			{
				ms_nShape.addEventListener(Event.ENTER_FRAME,enterFrameHandler);
			}
		}
		
		private function enterFrameHandler(event:Event):void
		{
			var nextTime:int = getTimer();
			var interval:int;
			if (ms_nPrevTime == 0)
			{
				interval = 0;
			}
			else
			{
				interval = Math.max(MIN_INTERVAL,Math.min(nextTime - ms_nPrevTime,MAX_INTERVAL));
				ms_nOnTimer(interval);
			}
			ms_nPrevTime = nextTime;
		}
	}
}